#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#       carga_archivo.py
#       
#       Copyright 2011 Cleve <mauricio.cleveland@gmail.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
#       
#       
import math

def Calcula_distancia((x1,y1), (x2,y2)):
  """Calcula distancia euclidiana"""
  
  xd = x2 - x1
  yd = y2 - y1
  
  return int(math.sqrt(xd*xd + yd*yd))

def Construye_matriz_distancia(coord):
  """hace matriz de distancia con las coordenadas
  pasadas
  """
  n = len(coord)
  
  D = [[0 for i in range(n)] for i in range(n)]      # lista
  for i in xrange(n-1):
      for j in xrange(i+1,n):
          
          (x1,y1) = coord[i]
          (x2,y2) = coord[j]
          D[i][j] = Calcula_distancia((x1,y1), (x2,y2))
          D[j][i] = D[i][j]
  
  
  return n,D

def Carga_archivo(ruta_archivo):
  """ Creacion de matriz

  @param ruta_archivo: Ruta de archivo TSPLIB
  @return none: n nodos y D Matriz de distancia del grafo de entrada.
  """
  nodo_coord = {}
  
  f = open(ruta_archivo, 'r')
  
  line = f.readline()
  while line.find("EDGE_WEIGHT_TYPE") == -1:
      line = f.readline()

  if line.find("EUC_2D") != -1:
      pass
  elif line.find("MAN_2D") != -1:
      pass
  else:
      print ("Only Euclidean distance.")
      raise Exception

  while line.find("NODE_COORD_SECTION") == -1:
      line = f.readline()

  xy_positions = []
  
  while 1:
      line = f.readline()
      if line.find("EOF") != -1: break
      (i,x,y) = line.split()
      x = float(x)
      y = float(y)
      nodo_coord[int(i)-1] = (x,y)
      xy_positions.append((x,y))

  f.close()
  
  nodos, matriz_distancia = Construye_matriz_distancia(xy_positions)
  
  return nodos, matriz_distancia, xy_positions, nodo_coord
